<template>
	<view class="uni-select">
		<uni-easyinput suffixIcon="bottom" v-model="selectText" @focus="toggle" :placeholder="title"></uni-easyinput>
		<uni-popup ref="popup">
			<view class="select-content">
				<view class="select-title">{{title}}</view>
				<view class="select-multiple-item" v-if="isMultiple">
					<uni-data-checkbox multiple v-model="multipleData" :localdata="data" />
				</view>
				<view class="select-item" v-else @click="selectedClick(item)" v-for="item in data" :value="item.value">
					{{item.text}}
				</view>
				<view class="select-btn" v-if="isMultiple"><u-button @click="multipleDataClick"
						type="primary">确认选择</u-button></view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		emits: ['onSelect'],
		props: {
			isMultiple: {
				type: Boolean,
				default: false
			},
			title: {
				type: String,
				default: ''
			},
			result: {
				type: Array,
				default: []
			}
		},
		data() {
			return {
				data: [],
				multipleData: [],
				selectText: "",
			}
		},
		watch: {
			result: {
				handler(newVal, oldVal) {
					this.data = newVal;
				},
				immediate: true,
				deep: true
			}
		},
		methods: {
			toggle() {
				uni.hideKeyboard()
				this.$refs.popup.open("bottom")
			},
			selectedClick(item) {
				this.selectText = item.text;
				this.$emit('onSelect', item);
				this.$refs.popup.close();
			},
			multipleDataClick() {
				let selectData = [];
				this.multipleData.forEach(item => {
					let obj = this.data.find((key) => {
						return key.value == item;
					});
					if (obj) {
						selectData.push(obj.text);
					}
				});
				this.selectText = selectData.join();
				this.$emit('onSelect', this.multipleData);
				this.$refs.popup.close();
			}
		}
	}
</script>

<style lang="scss">
	.uni-select {
		.select-content {
			background: #fff;
			height: 50vh;
			overflow-y: scroll;

			.select-text {
				color: #666;
			}

			.select-title {
				font-size: 18px;
				color: #666;
				text-align: center;
				padding: 10px 0;
			}

			.select-multiple-item {
				padding: 10px 15px;
				border-top: 1px solid #eee;
				display: flex;
				align-items: center;
				justify-content: space-around;

				.name {
					margin-left: 15px;
					color: #666;
				}
			}

			.select-item {
				padding: 10px 0;
				border-top: 1px solid #eee;
				text-align: center;
			}

			.select-btn {
				padding: 10px 15px;
			}
		}
	}
</style>